package com.sjn.gateway.config;

import com.netflix.loadbalancer.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: sjn
 * @Data: 2021/6/18 11:15
 */
@Component
public class HealthExamination implements IPing {

    @Override
    public boolean isAlive(Server server) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://" + server.getId() + "/test/heath";
        try {
            ResponseEntity<String> heath = restTemplate.getForEntity(url, String.class);
            if (heath.getStatusCode() == HttpStatus.OK) {
                System.out.println("ping " + url + " success and response is " + heath.getBody());
                return true;
            }
            System.out.println("ping " + url + " error and response is " + heath.getBody());
            return false;
        } catch (Exception e) {
            System.out.println("ping " + url + " failed");
            return false;
        }
    }
}
